package com.csw.android.androidtest.module.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.csw.android.androidtest.ui.LogViewFragment;
import com.csw.android.dev_utils.utils.FragmentHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 学自开源框架RxPermission,自从android6.0更新后，开发者需要动态获取权限，而权限回调则通过onActivityResult
 * 这无疑就跟需要权限请求的界面产生了很强的耦合，令人惊奇的是RxPermission居然可以做到监听回调，内部原理则是在
 * 需要动态权限请求的界面（Activity或fragment）添加一个无界面专门用于处理onActivityResult的fragment，然后
 * 通过接口回调进行解耦，牛逼。
 */
public class FragmentForSystemCallbackTest extends LogViewFragment {

    @Override
    public void initData() {
        super.initData();
        ImageSelector.getInstance(getChildFragmentManager()).selectAPicture(
                new ImageSelector.OnImageSelectListener() {
                    @Override
                    public void onSelected(Uri imageUri) {
                        logView.addLog(imageUri);
                    }

                    @Override
                    public void onCancel() {
                        logView.addLog("cancel select image");
                    }
                }
        );
    }

    /**
     * 这里展示如何通过fragment实现解耦系统图片选择，同样的用法还有很多，比如系统各种权限（比如悬浮窗权限），
     * 比如各种第三方登录（基本都是用onActivityResult回调）
     */
    public static final class ImageSelector extends Fragment {
        private AtomicInteger requestCodeProvider = new AtomicInteger(0);
        private Map<Integer, OnImageSelectListener> callbackHolder = new HashMap<>();

        public static ImageSelector getInstance(FragmentManager fragmentManager) {
            return FragmentHelper.INSTANCE.getFragmentInstance(fragmentManager, ImageSelector.class.getName(), ImageSelector.class);
        }

        public void selectAPicture(OnImageSelectListener listener) {
            if (requestCodeProvider.get() > 20) {
                requestCodeProvider.set(0);
            }
            int requestCode = requestCodeProvider.getAndIncrement();
            callbackHolder.put(requestCode, listener);
            //选择一张图片，任何图片类型
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, requestCode);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            OnImageSelectListener listener = callbackHolder.get(requestCode);
            if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
                listener.onSelected(data.getData());
            } else {
                listener.onCancel();
            }
        }

        public interface OnImageSelectListener {
            void onSelected(Uri imageUri);

            void onCancel();
        }
    }
}
